package com.tian.netty.executor;

import com.alibaba.fastjson.JSON;
import com.tian.netty.core.ClientChannelMap;
import com.tian.netty.message.ChargerCommLog;
import com.tian.netty.message.LogType;
import com.tian.netty.message.MsgType;
import com.tian.netty.message.req.ChargerLoginMsg;
import com.tian.netty.message.req.ChargerLoginReq;
import com.tian.netty.message.resp.ChargerLoginResp;
import com.tian.netty.util.MsgAndExecAnnotation;
import com.tian.util.DateUtils;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * {@code @description:} 充电桩登录报文识别处理
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-10 14:37
 * {@code @version:} 1.0
 */
@Slf4j
@Component(MsgType.MSG_TYPE_PRE + MsgType._0X_01)
public class ChargerLoginExecutor extends RequestExecutorBase {
    @Resource
    private RedissonClient redissonClient;

    @Override
    public void run() {
        ChargerLoginReq request = new ChargerLoginReq(MsgType._0X_01, msgObject);
        ChargerLoginMsg chargerLoginMsg = request.parse();

        ChargerLoginResp chargerLoginResp = new ChargerLoginResp(MsgType._0X_02);
        Map<String, Object> respBody = new HashMap<String, Object>();
        respBody.put("chargerNo", chargerLoginMsg.getChargeNo());
        respBody.put("currentTime", DateUtils.parse(DateUtils.formatDate(new Date()), "yyyyMMddHHmmss"));

        chargerLoginResp.setResponseBody(respBody);

        channel.writeAndFlush(chargerLoginResp.getMsgObject());

        SocketChannel hisChannel = ClientChannelMap.getSockeChannel(chargerLoginMsg.getChargeNo());
        //缓存连接
        if (hisChannel == null || hisChannel != channel) {
            ClientChannelMap.add(chargerLoginMsg.getChargeNo(), channel);
            //认证通过，保存电桩跟socketChannel的关系
            ClientChannelMap.add(chargerLoginMsg.getChargeNo(), channel);
            RBucket<String> bucket = redissonClient.getBucket("charger.online_" + chargerLoginMsg.getChargeNo());
            ChargerCommLog chargerCommLog = new ChargerCommLog();
            chargerCommLog.setChargerCode(chargerLoginMsg.getChargeNo());
            chargerCommLog.setLogType(LogType.ONLINE);
            chargerCommLog.setLogTime(new Date());
            chargerCommLog.setParams("client:" + channel.remoteAddress());
            bucket.set(JSON.toJSONString(chargerCommLog));
            log.info("充电桩登录成功，充电桩编号：{}", chargerLoginMsg.getChargeNo());
        }
    }
}
